import { ElMessage } from 'element-plus'
import LoginWork from './LoginWork'
import { ref } from 'vue'
import fileRequest from './fileRequest'

const isDownLoad = ref(false)

const sse = () => {
  const token = sessionStorage.getItem('Authorization')
  const eventSource = new EventSource(`/kl/sys/file/export/record/rt?token=${token}`)
  eventSource.onopen = function (event) {
    // ElMessage.success('连接成功')
    getDownloadList()
    isDownLoad.value = true
  }
  eventSource.addEventListener('message', function (e) {
    // ElMessage.success('message')
    // 如果change是true，调用分页。如果close是true，连接断开
    const res = JSON.parse(e.data)
    if (res.change) {
      getDownloadList()
    }
    if (res.close) {
      eventSource.close()
      ElMessage.success('生成成功，请点击下载')
      isDownLoad.value = false
      getDownloadList()
    }
  })
}

// 调用分页函数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getDownloadList()
}
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getDownloadList()
}
const downLoadList = ref([])
const getDownloadList = async () => {
  const res = (await LoginWork.post('/sys/file/export/record/page', {
    pageSize: pageSize.value,
    pageNum: currentPage.value
  })) as any
  if (res.code === 200) {
    downLoadList.value = res.data.rows
    total.value = res.data.total
  } else {
    ElMessage.error(res.msg)
  }
}

// 下载模块
const downLoad = async (item: any) => {
  const res = (await fileRequest.get(`/sys/file/export/record/download/${item.bucket}/${item.fileName}`)) as any
  const link = document.createElement('a') // 利用a标签自定义下载文件名
  let blob = new Blob([res.data]) // 创建Blob对象，设置文件类型
  link.style.display = 'none'
  //设置连接
  link.href = window.URL.createObjectURL(blob)
  const FileName = decodeURI(res.headers['content-disposition'].split(`fileName=`)[1])
  link.download = FileName //自定义文件名字
  document.body.appendChild(link)
  //模拟点击事件
  link.click()
  document.body.removeChild(link)
  getDownloadList()
}
const deleteDownLoad = async (item: any) => {
  const res = (await LoginWork.post(`/sys/file/export/record/remove/${item.id}`)) as any
  if (res.code === 200) {
    ElMessage.success('删除成功')
    getDownloadList()
  } else {
    ElMessage.error(res.message)
  }
}
export {
  sse,
  currentPage,
  pageSize,
  total,
  handleSizeChange,
  handleCurrentChange,
  downLoadList,
  isDownLoad,
  downLoad,
  deleteDownLoad,
  getDownloadList
}
